import React, { Component } from 'react';
import {
  Col,
  Table,
  Space,
  Row,
  Form,
  message,
  Tooltip,
  Input,
  Select,
  InputNumber,
  Button,
  Typography,
  DatePicker,
  Checkbox,
} from 'antd';

import 'antd/dist/antd.css';
import moment from 'moment';
import 'moment/locale/zh-cn';
import { getDictionaryLabel } from '../../../rudexRou/OperatesCookie.js';
import { checkAllNumber, getUrl } from '../../../utils';
import { addExam, getSubject } from '../../../api3';
import AdvancedSearchForm from '../../../componentJsx/common/searchForm';
import HasPermi from '../../../componentJsx/common/hasPermi';
// import NewModal from '../../../componentJsx/common/NewModal';
import '../../../componentCss/component.css';

export default class AddExam extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchForm: [
        {
          type: 'input',
          name: '题目名称',
          code: 'title',
          placeholder: '题目名称',
          maxLength: 50,
        },

        {
          type: 'select',
          name: '题目类型',
          code: 'type',
          options: getDictionaryLabel('questionType'),
        },
        // {
        //   type: 'select',
        //   name: '知识点',
        //   code: 'knowledge',
        //   options: getDictionaryLabel('questionKnowledge'),
        // },
        {
          type: 'input',
          name: '创建人',
          code: 'str',
          placeholder: '工号/姓名',
          maxLength: 20,
        },
      ],
      tableColumns: [
        {
          title: '题目名称',
          dataIndex: 'title',
          key: 'title',
          width: 240,
          fixed: 'left',
          ellipsis: true,
        },
        {
          title: '题目类型',
          dataIndex: 'type',
          key: 'type',
          width: 100,
          ellipsis: true,
          fixed: 'left',
          render: (text) => getDictionaryLabel('questionType', text),
        },
        {
          title: '知识点',
          dataIndex: 'knowledge',
          key: 'knowledge',
          ellipsis: true,
          width: 100,
        },
        {
          title: '可见范围',
          dataIndex: 'scope',
          key: 'scope',
          ellipsis: true,
          width: 80,
          render: (text) => getDictionaryLabel('questionScope', text),
        },
        {
          title: '用途',
          dataIndex: 'purpose',
          key: 'purpose',
          ellipsis: true,
          width: 80,
          render: (text) => getDictionaryLabel('questionPurpose', text),
        },
        {
          title: '创建人',
          dataIndex: 'createEmpName',
          key: 'createEmpName',
          ellipsis: true,
          width: 100,
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
          ellipsis: true,
          width: 160,
          render: (text) =>
            text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : text,
        },
        // {
        //   title: '最近修改人',
        //   dataIndex: 'updateName',
        //   key: 'updateName',
        //   ellipsis: true,
        //   width: 100,
        // },
        {
          title: '最近修改时间',
          dataIndex: 'updateTime',
          key: 'updateTime',
          ellipsis: true,
          width: 160,
          render: (text) =>
            text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : text,
        },
      ],
      selectedRowKeys: [],
      selectedRows: [],
      total: 0,
      pageSize: 10,
      page: 1,
      //数据
      tableData: [], //最新数据
      confirmLoading: false, //确认按钮异步等待
      tableLoading: false,
      subjectList: [],
      searchData: {},
      examLanguage: null,
      totalScore: 0,
      validity: null,
      examCont: 0,
      startTime: null,
    };
  }
  addForm = React.createRef();
  subjectForm = React.createRef();

  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys, selectedRows });
  };
  //修改页数changePage
  changePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.querySubject();
    });
  };
  execSearch = (data) => {
    // console.log(data);
    if (!this.state.examLanguage) return message.error('请先选择练习语言！', 3);
    this.setState({ searchData: data, page: 1 }, () => {
      this.querySubject();
    });
  };
  querySubject = () => {
    let searchData = this.state.searchData;
    let data = {};
    for (const key in searchData) {
      if (searchData[key] || searchData[key] === 0) {
        if (key == 'str') {
          checkAllNumber(searchData.str)
            ? (data.createEmpNo = searchData.str)
            : (data.createEmpName = searchData.str);
        } else {
          data[key] = searchData[key];
        }
      }
    }
    data.pageSize = this.state.pageSize;
    data.currentPage = this.state.page;
    data.purpose = '0';
    data.language = this.state.examLanguage;
    data.status = '2';
    getSubject(data)
      .then((res) => {
        if (res.data.code === 200) {
          if (res.data.data) {
            this.setState({
              total: res.data.data.total,
              tableData: res.data.data.list,
              tableLoading: false,
              selectedRowKeys: [],
              selectedRows: [],
            });
          } else {
            this.setState({
              total: 0,
              tableData: [],
              tableLoading: false,
              selectedRowKeys: [],
              selectedRows: [],
            });
          }
        } else {
          this.setState({ tableLoading: false });
          message.error(res.data.message || '查询数据失败!');
        }
      })
      .catch((err) => {
        this.setState({ tableLoading: false });
        message.error('查询数据失败!');
      });
  };
  buttonLoading = (flag) => {
    this.setState({ confirmLoading: flag });
  };
  addSubjectToExam = () => {
    let subjectList = [...this.state.subjectList];
    let defaultValue = {};
    let overMaxCount = false;
    this.state.selectedRows.map((_item, index) => {
      let obj = { ..._item };
      obj.score = 1;
      let flag = true;
      this.state.subjectList.forEach((item) => {
        if (item.id == obj.id) {
          flag = false;
          return message.warning(`【${item.title}】已添加，不能重复添加`, 3);
        }
      });
      if (subjectList.length >= 5) {
        overMaxCount = true;
        return;
        // return message.warning('最多只能选择5道题目', 3);
      }
      if (flag) {
        subjectList.push(obj);
        defaultValue[_item.id] = 1;
      }
    });
    if (overMaxCount) message.warning('最多只能选择5道题目', 3);
    this.setState(
      { subjectList, selectedRowKeys: [], selectedRows: [] },
      () => {
        this.subjectForm.current.setFieldsValue(defaultValue);
        this.getTotalScore();
      }
    );
  };
  deleteSubject = (id) => {
    let subjectList = [...this.state.subjectList];
    this.state.subjectList.forEach((item, index) => {
      if (item.id == id) subjectList.splice(index, 1);
    });
    this.setState({ subjectList }, () => {
      this.getTotalScore();
    });
  };
  addExam = () => {
    this.addForm.current.validateFields().then((values, error) => {
      if (error) return;
      if (this.state.subjectList.length <= 0) {
        return message.warning('请选择练习需要的题目', 3);
      }
      this.subjectForm.current.validateFields().then((values, error) => {
        if (error) return;
        let data = this.addForm.current.getFieldsValue();
        let subjectData = this.subjectForm.current.getFieldsValue();
        if (data.validity) {
          data.validity = data.validity[0];
          if (data.validity == '0') {
            data.validityBeginDate = data.validityDate[0].format('YYYY-MM-DD');
            data.validityEndDate = data.validityDate[1].format('YYYY-MM-DD');
            delete data.startTime;
          }
        } else if (data.startTime) {
          data.startTime = data.startTime.format('YYYY-MM-DD HH:mm:00');
          data.validity = '0';
        }

        data.type = '0';
        data.status = '0';
        delete data.validityDate;
        let questionList = [];
        for (const key in subjectData) {
          questionList.push({ questionId: key, score: subjectData[key] });
        }
        data.questionList = questionList;
        this.buttonLoading(true);
        addExam(data)
          .then((res) => {
            if (res.data.code === 200) {
              message.success('新增成功');
              this.buttonLoading(false);
              getUrl('/TmfsExam/PracticeManagement');
            } else {
              this.buttonLoading(false);
              message.error(res.data.message || '新增失败!');
            }
          })
          .catch((err) => {
            this.buttonLoading(false);
            message.error('新增失败!');
          });
      });
    });
  };
  languageChange = (value) => {
    if (value) {
      this.setState({ examLanguage: value }, () => {
        this.setState({
          subjectList: [],
          selectedRowKeys: [],
          selectedRows: [],
          page: 1,
        });
        this.querySubject();
      });
    } else {
      this.setState({ examLanguage: null });
    }
  };
  getTotalScore = () => {
    let subjectData = this.subjectForm.current.getFieldsValue();
    let totalScore = 0;
    for (const key in subjectData) {
      totalScore = totalScore + subjectData[key];
    }
    this.setState({ totalScore });
    this.addForm.current.setFieldsValue({ totalScore });
  };
  changeValidity = (value) => {
    // if(this.state.validity===)
    // console.log(value[value.length - 1]);
    if (value[value.length - 1]) {
      this.addForm.current.setFieldsValue({
        validity: [value[value.length - 1]],
      });
    } else {
      this.addForm.current.setFieldsValue({
        validity: [],
      });
    }
    this.setState({ validity: value[value.length - 1] });
  };
  clickValidity = (e) => {
    // console.log(e);
  };
  changeExamCont = (value) => {
    this.setState({ examCont: value });
  };
  changeStartTime = (value) => {
    if (value) {
      this.addForm.current.setFieldsValue({ count: 1 });
    }
    this.setState({ startTime: value });
  };
  changeValidityDate = (value) => {
    this.setState({ validityDate: value });
  };
  buttonLoading = (flag) => {
    this.setState({ confirmLoading: flag });
  };
  componentDidMount() {
    this.addForm.current.setFieldsValue({ count: 0 });
  }
  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }
  render() {
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: this.onSelectChange,
    };

    const disabledDate = (time) => {
      if (!this.state.validityDate) {
        return time < moment().subtract(1, 'day');
      } else {
        return (
          (time && time > this.state.validityDate[1]) ||
          (time &&
            time < moment(this.state.validityDate[0].format('YYYY-MM-DD')))
        );
      }
    };
    return (
      <div className='examWrap'>
        <div>
          <div className='examTitle'>新增练习：</div>
          <Form labelAlign='left' name='addForm' ref={this.addForm}>
            <Row gutter={[20]}>
              <Col span={9}>
                <Form.Item
                  label='练习名称'
                  name='name'
                  rules={[{ required: true, message: '请输入' }]}
                >
                  <Input maxLength={50} />
                </Form.Item>
              </Col>
              <Col span={5}>
                <Form.Item
                  label='练习级别'
                  name='level'
                  rules={[{ required: true, message: '请选择' }]}
                >
                  <Select
                    placeholder='请选择'
                    allowClear
                    showSearch
                    filterOption={(input, option) =>
                      option.children
                        .toLowerCase()
                        .indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    {getDictionaryLabel('examLevel').map((item) => (
                      <Select.Option key={item.code} value={item.code}>
                        {item.label}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={5}>
                <Form.Item
                  label='练习语言'
                  name='language'
                  rules={[{ required: true, message: '请选择' }]}
                >
                  <Select
                    onChange={this.languageChange}
                    placeholder='请选择'
                    allowClear
                    showSearch
                    filterOption={(input, option) =>
                      option.children
                        .toLowerCase()
                        .indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    {getDictionaryLabel('questionLanguage').map((item) => (
                      <Select.Option key={item.code} value={item.code}>
                        {item.label}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={5}>
                <Form.Item
                  label='练习类型'
                  name='open'
                  rules={[{ required: true, message: '请选择' }]}
                >
                  <Select placeholder='请选择' allowClear>
                    {/* <Select.Option key={0} value='0'>
                      邀请
                    </Select.Option>
                    <Select.Option key={1} value='1'>
                      公开
                    </Select.Option> */}
                    {getDictionaryLabel('testExamType').map((item) => (
                      <Select.Option key={item.code} value={item.code}>
                        {item.label}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              {this.state.validity ? null : (
                <Col>
                  <Tooltip
                    title='设置 “练习开始时间” 时不能设置是否 “永久有效”'
                    overlayStyle={{ minWidth: '320px' }}
                  >
                    <Form.Item
                      label='练习开始时间'
                      name='startTime'
                      rules={[
                        {
                          required: true,
                          message: '请选择',
                        },
                      ]}
                    >
                      <DatePicker
                        disabledDate={disabledDate}
                        onChange={this.changeStartTime}
                        style={{ width: '100%' }}
                        showTime={{
                          format: 'HH:mm',
                          defaultValue: moment('00:00', 'HH:mm'),
                        }}
                        format='YYYY-MM-DD HH:mm'
                        allowClear
                      />
                    </Form.Item>
                  </Tooltip>
                </Col>
              )}

              {this.state.startTime ? null : (
                <>
                  <Col>
                    <Tooltip
                      title='设置是否 “永久有效” 时不能设置 “练习开始时间”'
                      overlayStyle={{ minWidth: '320px' }}
                    >
                      <Form.Item
                        label='永久有效'
                        name='validity'
                        rules={[{ required: true, message: '请选择' }]}
                      >
                        <Checkbox.Group
                          onChange={this.changeValidity}
                          onClick={this.clickValidity}
                        >
                          <Checkbox value='1'>是</Checkbox>
                          <Checkbox value='0'>否</Checkbox>
                        </Checkbox.Group>
                      </Form.Item>
                    </Tooltip>
                  </Col>
                  {this.state.validity == '0' ? (
                    <Col>
                      <Form.Item
                        label='有效期'
                        name='validityDate'
                        rules={[{ required: true, message: '请选择' }]}
                      >
                        <DatePicker.RangePicker
                          onChange={this.changeValidityDate}
                          style={{ minWidth: 200, width: '100%' }}
                          disabledDate={(current) => {
                            return current < moment().subtract(1, 'day');
                          }}
                          allowClear
                        />
                      </Form.Item>
                    </Col>
                  ) : null}
                </>
              )}
            </Row>
            <Row gutter={[20]}>
              <Col>
                <Form.Item
                  label='练习时长(min)'
                  name='duration'
                  rules={[{ required: true, message: '请输入' }]}
                >
                  <InputNumber min={1} max={1000} precision={0} />
                </Form.Item>
              </Col>
              <Col>
                <Form.Item
                  label='总分'
                  name='totalScore'
                  rules={[{ required: true, message: '请输入' }]}
                >
                  <InputNumber disabled precision={0} min={1} max={100000} />
                </Form.Item>
              </Col>
              <Col>
                <Form.Item
                  label='及格分'
                  name='passScore'
                  rules={
                    this.state.totalScore
                      ? [
                          { required: true, message: '请输入' },
                          {
                            type: 'number',
                            min: 1,
                            max: this.state.totalScore,
                            message: '不得大于总分',
                          },
                        ]
                      : null
                  }
                >
                  <InputNumber
                    // disabled={this.state.totalScore?false:true}
                    precision={0}
                    min={1}
                    // max={this.state.totalScore}
                  />
                </Form.Item>
              </Col>
              <Col>
                <Form.Item
                  label='练习次数'
                  name='count'
                  rules={[{ required: true, message: '请输入' }]}
                >
                  <InputNumber
                    disabled={this.state.startTime ? true : false}
                    onChange={this.changeExamCont}
                    precision={0}
                    min={0}
                    max={100000}
                  />
                </Form.Item>
              </Col>
              <Col>
                <Typography.Text
                  type='secondary'
                  style={{ lineHeight: '32px' }}
                >
                  注：0为无限次
                </Typography.Text>
              </Col>
            </Row>
          </Form>
        </div>
        <div>
          <div className='examTitle'>题目设置：</div>
          <div>
            <AdvancedSearchForm
              execSearch={this.execSearch}
              formData={this.state.searchForm}
            />
          </div>
          <div>
            <HasPermi
              bottonData={{
                interceptor: 'tmfsExamPlatform:practiceManagement:edit',
                clickFn: this.addSubjectToExam,
                text: '添加题目',
                disabled:
                  this.state.selectedRows.length == 0 ||
                  this.state.subjectList.length >= 5
                    ? true
                    : false,
              }}
            />
            <Typography.Text type='secondary' style={{ marginLeft: 12 }}>
              注：最多选择5道题目
            </Typography.Text>
          </div>
          <div>
            <Table
              rowKey='id'
              loading={this.state.lastLoading}
              style={{ marginTop: 10 }}
              scroll={{ x: '100' }}
              rowSelection={{ type: 'checkbox', ...rowSelection }}
              columns={this.state.tableColumns}
              dataSource={this.state.tableData}
              pagination={{
                total: this.state.total,
                pageSize: this.state.pageSize,
                current: this.state.page,
                showSizeChanger: true,
                onChange: this.changePage,
                showTotal: (total) => '共 ' + total + ' 条',
              }}
              size='small'
              // bordered
            />
          </div>
        </div>
        <div>
          <div className='examTitle'>已添加题目：</div>
          <div>
            <Form ref={this.subjectForm}>
              {this.state.subjectList.length ? (
                this.state.subjectList.map((item, index) => {
                  return (
                    <Row key={item.id}>
                      <Col span={8}>
                        <Form.Item label={'题目' + (index + 1)}>
                          {item.title}
                        </Form.Item>
                      </Col>
                      <Col span={6}>
                        <Form.Item
                          label='分数'
                          name={item.id}
                          rules={[
                            { required: true, message: '请输入题目成绩' },
                            {
                              type: 'number',
                              min: 1,
                              max: 100,
                              message: '分值范围为1-100',
                            },
                          ]}
                        >
                          <InputNumber
                            onChange={this.getTotalScore}
                            min={1}
                            max={100}
                            precision={0}
                            style={{ width: '90%' }}
                          />
                        </Form.Item>
                      </Col>
                      <Col span={6}>
                        <HasPermi
                          bottonData={{
                            type: 'danger',
                            interceptor:
                              'tmfsExamPlatform:practiceManagement:edit',
                            clickFn: () => this.deleteSubject(item.id),
                            text: '删除',
                          }}
                        />
                      </Col>
                    </Row>
                  );
                })
              ) : (
                <div
                  style={{
                    textAlign: 'left',
                    color: 'rgba(0,0,0,0.35)',
                    marginBottom: '30px',
                  }}
                >
                  暂无已添加题目
                </div>
              )}
            </Form>
          </div>
        </div>
        <div className='bottomBtnBorder'>
          <Space>
            <Button
              onClick={() => {
                getUrl('/TmfsExam/PracticeManagement');
              }}
            >
              返回
            </Button>
            <HasPermi
              bottonData={{
                type: 'primary',
                interceptor: 'tmfsExamPlatform:practiceManagement:edit',
                clickFn: this.addExam,
                text: '确认',
                loading: this.state.confirmLoading,
              }}
            />
          </Space>
        </div>
      </div>
    );
  }
}
